package com.nioEx;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class SocketChannelEx {

	public static void main(String[] args) throws IOException {

		String host = "www.mtime.com";
		Selector selector = Selector.open();

		SocketChannel sc = SocketChannel.open(new InetSocketAddress(host, 80));

		sc.configureBlocking(false);

		sc.register(selector, SelectionKey.OP_READ);

		while (true) {

			if (selector.select() <= 0)
				continue;

			Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
			while (iter.hasNext()) {

				SelectionKey key = iter.next();

				iter.remove();

				handleKey(key);

			}

		}

	}

	public static void handleKey(SelectionKey key) throws IOException {
		if (key.isReadable()) {
			ByteBuffer b = ByteBuffer.allocate(1024);
			SocketChannel ss = (SocketChannel) key.channel();

			if (ss.read(b) > 0) {
				b.flip();
				byte[] a = new byte[b.limit()];
				b.get(a);
				System.out.println("Server >>" + new String(a));
				b.clear();

			}

		}

	}
}
